package com.system.manager.modules.projectLibrary.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.system.manager.common.entity.Result;
import com.system.manager.common.enums.ErrorCode;
import com.system.manager.common.exception.SysException;
import com.system.manager.modules.authorized.entity.Subject;
import com.system.manager.modules.authorized.entity.User;
import com.system.manager.modules.authorized.mapper.UserMapper;
import com.system.manager.modules.projectLibrary.dto.UsernamePassword;
import com.system.manager.modules.projectLibrary.entity.Enterprise;
import com.system.manager.modules.projectLibrary.entity.ProjectLeader;
import com.system.manager.modules.projectLibrary.enums.ProjectLibraryErrorCode;
import com.system.manager.modules.projectLibrary.exception.ProjectLibraryException;
import com.system.manager.modules.projectLibrary.mapper.EnterpriseMapper;
import com.system.manager.modules.projectLibrary.mapper.ProjectLeaderMapper;
import com.system.manager.modules.projectLibrary.service.IEnterpriseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.manager.utils.MD5Utils;
import com.system.manager.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jisf
 * @since 2021-11-03
 */
@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements IEnterpriseService {

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ProjectLeaderMapper projectLeaderMapper;


    /**
     * TODO 项目负责人录入单位信息
     *
     * @param enterprise
     * @return
     */
    @Override
    public UsernamePassword insertEnterprise(Enterprise enterprise) {
        String name = enterprise.getName();
        String code = enterprise.getCode();
        if (name == null) {
            throw new ProjectLibraryException(ProjectLibraryErrorCode.NAME_NOT_NULL);
        }
        if (code == null) {
            throw new ProjectLibraryException(ProjectLibraryErrorCode.CODE_NOT_NULL);
        }

        //判断单位名称是否存在
        Integer idByName = enterpriseMapper.selectFirmIdByName(name);
        if (idByName != null) {
            throw new ProjectLibraryException(ProjectLibraryErrorCode.FIRM_NAME_ALREADY_EXIST);
        }

        //判断单位组织机构代码是否存在
        Integer idByCode = enterpriseMapper.selectFirmIdByCode(code);
        if (idByCode != null) {
            throw new ProjectLibraryException(ProjectLibraryErrorCode.FIRM_CODE_ALREADY_EXIST);
        }
        //根据单位名称和单位组织机构代码来进行加锁，防止在并发情况下出现名字或者组织机构代码一样
        synchronized (name) {
            synchronized (code) {
                //判断单位名称是否存在
                idByName = enterpriseMapper.selectFirmIdByName(name);
                if (idByName != null) {
                    throw new ProjectLibraryException(ProjectLibraryErrorCode.FIRM_NAME_ALREADY_EXIST);
                }

                //判断单位组织机构代码是否存在
                idByCode = enterpriseMapper.selectFirmIdByCode(code);
                if (idByCode != null) {
                    throw new ProjectLibraryException(ProjectLibraryErrorCode.FIRM_CODE_ALREADY_EXIST);
                }

                //根据组织机构代码为单位设置账号
                enterprise.setUsername(code + UUIDUtils.randomUUID().substring(0, 8));

                //设置密码
                if (enterprise.getPassword() == null || enterprise.getPassword().equals("")) {
                    enterprise.setPassword(UUIDUtils.randomUUID().substring(0, 8));
                }

                //插入单位信息
                try {
                    enterpriseMapper.insert(enterprise);
                } catch (Exception e) {
                    throw new SysException();
                }

                User user = new User();
                user.setUserAccount(enterprise.getUsername());
                user.setPassword(MD5Utils.Base64Encode(enterprise.getPassword()));
                user.setName(enterprise.getName());
                user.setPhone(enterprise.getPhone());
                user.setOrganizationId(enterprise.getId());
                user.setStatus(0);
                user.setRole(2);
                try {
                    userMapper.insert(user);
                }catch (Exception e){
                    throw new SysException();
                }

                //返回用户名和密码
                Integer id = enterprise.getId();
                if (id != null) {
                    UsernamePassword usernamePassword = selectUsernamePassword(id);
                    return usernamePassword;
                }
            }
        }

        return null;
    }


    /**
     * TODO 根据单位id查询用户名密码
     * （这里未做权限认证，所以不对外开放）
     *
     * @param id
     * @return
     */
    private UsernamePassword selectUsernamePassword(Integer id) {
        try {
            UsernamePassword usernamePassword = enterpriseMapper.selectUsernamePasswordById(id);
            return usernamePassword;
        } catch (Exception e) {
            throw new ProjectLibraryException(ErrorCode.SYSTEM_FAILED);
        }
    }

    /**
     * TODO 修改单位信息
     *
     * @param enterprise
     * @param subject
     */
    @Override
    public void updateEnterprise(Enterprise enterprise, Subject subject) {

        //判断当前用户是否有权限
        Integer id = subject.getId();
        User user = userMapper.selectById(id);
        //获取用户账户
        String account = user.getUserAccount();
        //获取用户角色
        Integer role = user.getRole();
        if (role == 2) {
            //判断该企业管理员是否属于被修改公司的
            QueryWrapper<Enterprise> queryWrapperEnterprise = new QueryWrapper<>();
            queryWrapperEnterprise.select("id").eq("username", account);
            Integer enterpriseId = enterpriseMapper.selectOne(queryWrapperEnterprise).getId();
            if (enterpriseId != enterprise.getId()) {
                throw new ProjectLibraryException(ProjectLibraryErrorCode.USER_HAS_NO_PERMISSIONS);
            }
        } else {
            throw new ProjectLibraryException(ProjectLibraryErrorCode.USER_HAS_NO_PERMISSIONS);
        }

//        修改单位信息后，单位状态变为已申请未验证
        enterprise.setVerify(0);
        //修改单位信息
        UpdateWrapper<Enterprise> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", enterprise.getId());
        try {
            enterpriseMapper.update(enterprise, updateWrapper);
        } catch (Exception e) {
            throw new SysException();
        }
    }

    /**
     * TODO 展示本单位的信息
     *
     * @param subject
     * @return
     */
    @Override
    public Enterprise selectEnterprise(Subject subject) {
        //获取访问用户的username
        String username = userMapper.selectById(subject.getId()).getUserAccount();

        //获取访问用户的firm
        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);

        //查询单位信息
        Enterprise enterprise = enterpriseMapper.selectOne(queryWrapper);
        return enterprise;
    }

    /**
     * TODO 单位审核
     *
     * @param subject
     * @return
     */
    @Override
    public String auditEnterprise(Integer id, Subject subject, Integer verify) {
        Integer role = userMapper.selectById(subject.getId()).getRole();
        UpdateWrapper<Enterprise> updateWrapper = new UpdateWrapper<>();
        String message = "";
        if (role == 2) {  //企业管理员
            updateWrapper.set("verify", 0);
            message = "该单位已提交审核";
        } else if (role == 5) {    //商委部门人员
            updateWrapper.set("verify", verify);
            if (verify == 1) {
                message = "已通过该单位的申请";
            } else if (verify == -1) {
                message = "已拒绝该单位的申请";
            } else {
                throw new ProjectLibraryException(ProjectLibraryErrorCode.PARAMETER_UNRECOGNIZED);
            }

        }
        updateWrapper.eq("id", id);
        try {
            enterpriseMapper.update(new Enterprise(), updateWrapper);
        } catch (Exception e) {
            throw new SysException();
        }
        return message;
    }

    /**
     * TODO 查询所有申请单位
     *
     * @return
     */
    @Override
    public Result selectAllEnterprise(Integer currPage, Integer size, String name, String code, String username, String verifyStr) {
        IPage<Enterprise> enterpriseIPage = new Page<>(currPage, size);
        //查询所有对象，并进行分页封装
        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper<>();

        if(name != null && !name.equals("")){
            queryWrapper.eq("name",name);
        }
        if(code != null && !code.equals("")){
            queryWrapper.eq("code",code);
        }
        if(username != null && !username.equals("")){
            queryWrapper.eq("username",username);
        }
        System.out.println("verifyStr:"+verifyStr+"------");
        if(verifyStr != null && !verifyStr.equals("")){
            switch (verifyStr) {
                case "已申请":
                    queryWrapper.eq("verify",0);
                    break;
                case "已验证":
                    queryWrapper.eq("verify",1);
                    break;
                case "已拒绝":
                    queryWrapper.eq("verify",-1);
                    break;
                default:
                    break;
            }
        }

        page(enterpriseIPage, queryWrapper);
        //数据
        List<Enterprise> enterprises = enterpriseIPage.getRecords();
        //所有数据总数
        int total = (int) enterpriseIPage.getTotal();

        return Result.ok(enterprises, total);

    }

    @Override
    public List<Enterprise> selectInitEnterprise() {
        List<Enterprise> enterprises = enterpriseMapper.selectList(new QueryWrapper<>());
        return enterprises;
    }
}
